<template>
	<div>
		<div class="user-top" style="height: 100vh;overflow: scroll;">
			<van-nav-bar title="个人主页" :style="navBarStyle">
				<template #right>
					<van-icon style="font-size: 1.5rem;" name="chat-o" />
				</template>
			</van-nav-bar>

			<div>
				<van-pull-refresh v-model="refreshing" @refresh="reflashList" @scroll="handleScroll"
					style="height: calc(100vh - 46px);overflow: scroll;">
					<div style="height: 10vh;">
						&nbsp;
					</div>
					<div class="halfCard">
						<van-skeleton title avatar :row="3" :loading="!userData.loaded" style="background: white;">

						</van-skeleton>
						<table v-show="userData.loaded" style="--van-button-plain-background	:rgba(0,0,0,0)">
							<tr>
								<td v-if="!((typeof userData.user.headImgSrc)=== 'undefined')">
									<van-image style="margin: 2vh;" width="20vw" height="20vw" fit="cover"
										:src="urlIp+'/'+userData.user.headImgSrc" round />
								</td>
								<td style="width: 5vw;">
									&nbsp;
								</td>
								<td>
									<table style="text-align: center;line-height: 3vw;font-size: 3vw;">
										<tr style="height: calc( 5vw + 2vh );">
											<td>&nbsp;</td>
										</tr>

										<tr>
											<van-row style="width: calc(100vw - 20vw - 4vh - 5vw - 2vh - 2vw );">
												<van-col span="12" style="text-align: center;">
													<table style="text-align: center;display: inline-block;">
														<tr>
															<td>
																<strong>
																	{{userData.fansNumber}}
																</strong>
															</td>
														</tr>
														<tr>
															<td style="color: gray;">
																粉丝
															</td>
														</tr>
													</table>
												</van-col>
												<van-col span="12" style="text-align: center;">
													<table style="text-align: center;display: inline-block;">
														<tr>
															<td>
																<strong>
																	{{userData.subscribeNumber}}
																</strong>
															</td>
														</tr>
														<tr>
															<td style="color: gray;">
																关注
															</td>
														</tr>
													</table>
												</van-col>
											</van-row>
										</tr>
										<tr>
											<van-button @click="subscribe" block plain icon="plus" v-if="userData.subscribeState==='NONE'">关注</van-button>
											<van-button @click="cancelSub" block plain icon="cross" v-if="userData.subscribeState==='SUB'">取消关注</van-button>
											<van-button @click="subscribe" block plain icon="revoke" v-if="userData.subscribeState==='BE'">回关</van-button>
											<van-button @click="cancelSub" block plain icon="exchange" v-if="userData.subscribeState==='EACH'">取消回关</van-button>
										</tr>
									</table>
								</td>
							</tr>

							<tr>
								<td style="padding: 1rem;">
									<div style="font-size: 1.5rem;font-weight: 700;margin-bottom: 2vh; color: black;">
										{{userData.user.username}}
									</div>
								</td>
							</tr>
						</table>
					</div>



					<div>
						<div style="background-color: #FAFAFA;">
							<van-tabs v-model:active="listRouterPath" swipeable>
								<van-tab title="动态">
									<div v-show="loading[0]">
										<div>
											&nbsp;
										</div>
										<van-skeleton title avatar :row="3" />
										<div>
											&nbsp;
										</div>
										<van-skeleton title avatar :row="3" />
										<div>
											&nbsp;
										</div>
									</div>
									
									<div style=" text-align: center;" v-if="(list[0].length===0)&&(pages[0].noMore)">
										<van-empty image="/imgs/blogEmpty.jpg" image-size="15rem"
											description="暂时还没有帖子" />
									</div>
									<div v-else>
										<van-list v-model:loading="loading[0]"
											:finished="pages[0].noMore" finished-text="没有更多了"
											@load="pushBlog">
											<van-cell v-for="(blog,key) in list[0]" :key="key" style="margin-top: 1%;">
												<BlogWithComment :data="blog"></BlogWithComment>
											</van-cell>
										</van-list>
									</div>
								</van-tab>
								<van-tab title="求助">
									<div v-show="loading[1]">
										<div>
											&nbsp;
										</div>
										<van-skeleton title avatar :row="3" />
										<div>
											&nbsp;
										</div>
										<van-skeleton title avatar :row="3" />
										<div>
											&nbsp;
										</div>
									</div>
									<div style="text-align: center;" v-if="(list[1].length===0)&&(pages[1].noMore)">
										<van-empty image="/imgs/offerEmpty.jpg" image-size="15rem"
											description="暂时还没有求助" />
									</div>
									<div v-else>
										<van-list v-model:loading="loading[1]" :finished="pages[1].noMore"
											finished-text="没有更多了" @load="pushOffer">
											<van-cell v-for="(offer,key) in list[1]" :key="key" style="margin-top: 1%;">
												<OfferCell :data="offer" :accept="acceptOfferButtonHandler"></OfferCell>
											</van-cell>
										</van-list>
									</div>
								</van-tab>
								<van-tab title="闲置">
									<div v-show="loading[2]">
										<div>
											&nbsp;
										</div>
										<van-skeleton title avatar :row="3" />
										<div>
											&nbsp;
										</div>
										<van-skeleton title avatar :row="3" />
										<div>
											&nbsp;
										</div>
									</div>
									<div style="text-align: center;" v-if="(list[2].length===0)&&(pages[2].noMore)">
										<van-empty image="/imgs/goodEmpty.jpg" image-size="15rem"
											description="暂时还没有闲置" />

									</div>
									<div v-else>
										<van-list v-model:loading="loading[2]" :finished="pages[2].noMore"
											finished-text="没有更多了" @load="pushGoods">
											<van-cell v-for="(good,key) in list[2]" :key="key" style="margin-top: 1%;">
												<GoodCell :openDetailPage="showDetailPage" :data="good"></GoodCell>
											</van-cell>
										</van-list>
									</div>
								</van-tab>
							</van-tabs>

						</div>
					</div>
				</van-pull-refresh>
			</div>
		</div>
		<div>
			<van-popup v-model:show="detailPage" position="right" :style="{ width: '100%', height: '100%' }" closeable
				close-icon="arrow-left" close-icon-position="top-left" :before-close="detailPageCloseEvent">
				<GoodDetailPage :goodData="detailPageData" v-if="detailPageFlash" :showPayPage="showPayHandler"
					ref="goodDetailPage" :openSellerPage="closeDetailPage"></GoodDetailPage>
			</van-popup>
			<van-popup v-model:show="payPageShow" position="right" :style="{ width: '100%', height: '100%' }" closeable
				close-icon="arrow-left" close-icon-position="top-left">
				<PayPage></PayPage>
			</van-popup>
		</div>
	</div>
</template>

<script>
	import {
		showNotify,
		showConfirmDialog,
		showLoadingToast
	} from 'vant';
	import url from '@/assets/url.json';
	import BlogWithComment from '@/components/units/BlogWithComment.vue';
	import GoodDetailPage from './GoodDetailPage.vue';
	import PayPage from './PayPage.vue';
	import OfferCell from '@/components/units/OfferCell.vue';
	import GoodCell from '@/components/units/GoodCell.vue';
	

	export default {
		name: 'UserHomePage',
		props: {
			uid: String
		},

		components: {
			BlogWithComment,
			GoodDetailPage,
			PayPage,
			OfferCell,
			GoodCell
		},

		data() {
			return {
				urlIp: url.ip,
				navBarStyle: "--van-nav-bar-background:rgba(0,0,0,0)",
				transparentBackground: "--van-nav-bar-background:rgba(0,0,0,0)",
				whiteBackground: "",

				userData: {
					loaded: false,
					user: {
						headImgUrl: '',
						userName: '',
					},
					fansNumber: 0,
					subscribeNumber: 0,
					subscribeState: 'NONE',
				},

				blogList: [],
				offerList: [],
				goodsList: [],
				refreshing: false,
				listRouterPath: 0,
				list: [
					[],
					[],
					[]
				],
				loading: [
					false,
					false,
					false
				],
				pages: [{
						page: 0,
						limit: 5,
						noMore: false
					},
					{
						page: 0,
						limit: 5,
						noMore: false
					},
					{
						page: 0,
						limit: 5,
						noMore: false
					},
				],

				// 商品
				detailPageExist: false,
				detailPage: false,
				detailPageData: {},
				detailPageFlash: true,
				payPageShow: false,

			}
		},
		mounted() {
			this.loadUser();
			this.pushBlog();
			this.pushOffer();
			this.pushGoods();
		},

		watch: {
			uid: {
				handler(newVal, oldVal) {
					console.log(newVal, oldVal)
					this.change();
				}
			}
		},

		methods: {
			subscribe(){
				if(this.$cookies.get('userId')===this.uid){
					showNotify({
						type: 'danger',
						message: "不能关注自己"
					});
					return;
				}
				this.$axios({
					url: url.ip + '/api-user/subcribe',
					method: 'PUT',
					headers: {
						token: this.$cookies.get('token'),
					},
					data:{
						id: this.$cookies.get('userId'),
						beScribeId: this.uid
					}
				}).then((res) => {
					if (res.data.code === 0) {
						if(this.userData.subscribeState==='NONE'){
							this.userData.subscribeState='SUB';
						}
						if(this.userData.subscribeState==='BE'){
							this.userData.subscribeState='EACH';
						}
					} else {
						showNotify({
							type: 'danger',
							message: res.data.message
						});
					}
				}).catch((err) => {
					console.log(err);
					showNotify({
						type: 'danger',
						message: "网络错误或未登录"
					});
				})
			},
			cancelSub(){
				if(this.$cookies.get('userId')===this.uid){
					showNotify({
						type: 'danger',
						message: "不能关注自己"
					});
					return;
				}
				this.$axios({
					url: url.ip + '/api-user/subcribe/delete',
					method: 'DELETE',
					headers: {
						token: this.$cookies.get('token'),
					},
					data:{
						id: this.$cookies.get('userId'),
						beScribeId: this.uid
					}
				}).then((res) => {
					if (res.data.code === 0) {
						if(this.userData.subscribeState==='SUB'){
							this.userData.subscribeState='NONE';
						}
						if(this.userData.subscribeState==='EACH'){
							this.userData.subscribeState='BE';
						}
					} else {
						showNotify({
							type: 'danger',
							message: res.data.message
						});
					}
				}).catch((err) => {
					console.log(err);
					showNotify({
						type: 'danger',
						message: "网络错误或未登录"
					});
				})
			},


			change() {
				this.loadUser();
				let f = (p) => {
					this.pages[p].noMore = false;
					this.pages[p].page = 0;
					this.list[p] = [];
					switch (this.listRouterPath) {
						case 0:
							this.pushBlog();
							break;
						case 1:
							this.pushOffer();
							break;
						case 2:
							this.pushGoods();
							break;
					}
				}
				for (let i = 0; i < 3; i++) {
					f(i);
				}
			},
			loadUser() {
				this.userData.loaded = false;
				let fansCount = () => {
					this.$axios({
						url: url.ip + '/api-user/home/fans/count?id=' + this.uid,
						method: 'GET',
						headers: {
							token: this.$cookies.get('token'),
						}
					}).then((res) => {
						if (res.data.code !== 0) {
							showNotify({
								type: 'danger',
								message: res.data.message
							});
						} else {
							this.userData.fansNumber = res.data.data

						}
					})
				}
				let subcribeCount = () => {
					this.$axios({
						url: url.ip + '/api-user/home/subcribe/count?id=' + this.uid,
						method: 'GET',
						headers: {
							token: this.$cookies.get('token'),
						}
					}).then((res) => {
						if (res.data.code !== 0) {
							showNotify({
								type: 'danger',
								message: res.data.message
							});
						} else {
							this.userData.subscribeNumber = res.data.data

						}
					})
				}
				let subcribeState = () => {
					this.$axios({
						url: url.ip + '/api-user/subcribe/state/'+ this.$cookies.get('userId') +'/' + this.uid,
						method: 'GET',
						headers: {
							token: this.$cookies.get('token'),
						}
					}).then((res) => {
						if (res.data.code !== 0) {
							showNotify({
								type: 'danger',
								message: res.data.message
							});
						} else {
							this.userData.subscribeState = res.data.data
						}
					})
				}
				
				fansCount();
				subcribeCount();
				subcribeState();

				this.$axios({
					url: url.ip + '/api-user/user/id',
					method: 'GET',
					headers: {
						token: this.$cookies.get('token'),
					},
					params: {
						id: this.uid
					}
				}).then((res) => {
					if (res.data.code === 0) {
						this.userData.user = res.data.data[0];
						this.userData.loaded = true;
					} else {
						showNotify({
							type: 'danger',
							message: res.data.message
						});
					}
				}).catch((err) => {
					console.log(err);
					showNotify({
						type: 'danger',
						message: "网络错误或未登录"
					});
				})
			},



			handleScroll(e) {
				if (e.srcElement.scrollTop > (this.viewportToPixels('10vh') + this.viewportToPixels('6vw'))) {
					this.navBarStyle = this.whiteBackground;
				} else {
					this.navBarStyle = this.transparentBackground;
				}
			},
			viewportToPixels(value) {
				var parts = value.match(/([0-9\\.]+)(vh|vw)/)
				var q = Number(parts[1])
				var side = window[['innerHeight', 'innerWidth'][
					['vh', 'vw'].indexOf(parts[2])
				]]
				return side * (q / 100)
			},
			reflashList() {
				this.loadUser();
				/* 
				 * this.listRouterPath:
				 * 0: 动态, blog
				 * 1: 求助, offer
				 * 2: 闲置, goods
				 */
				let p = this.listRouterPath
				// this.pages[p].noMore = false;
				this.pages[p].page = 0;
				this.list[p] = [];
				switch (this.listRouterPath) {
					case 0:
						this.pushBlog();
						break;
					case 1:
						this.pushOffer();
						break;
					case 2:
						this.pushGoods();
						break;
				}
			},
			pushBlog() {
				this.pushData(0, '/api-blog' + '/blog/user_blog/', (res) => {
					return res.data.data.blogList;
				})
			},
			pushOffer() {
				this.pushData(1, '/api-offer' + '/offer/byId', (res) => {
					return res.data.data;
				})
			},
			pushGoods() {
				this.pushData(2, '/api-goods' + '/goods/getGoodsByUid', (res) => {
					return res.data.data.entityList;
				})
			},
			pushData(p, src, getData) {
				this.pages[p].page += 1;
				this.$axios({
					url: url.ip + src,
					method: 'GET',
					params: {
						page: this.pages[p].page,
						limit: this.pages[p].limit,
						id: this.uid
					},
					headers: {
						token: this.$cookies.get('token'),
					}
				}).then((res) => {
					if (res.data.code !== 0) {
						this.pages[p].noMore = true;
						showNotify({
							type: 'danger',
							message: res.data.message
						});
					} else {
						let dataList = getData(res);
						if (dataList.length <= 0) {
							this.pages[p].noMore = true;
						} else {
							for (let key in dataList) {
								this.list[p].push(dataList[key]);
							}
							this.pages[p].noMore = false;
						}
					}
					this.loading[p] = false;
					this.refreshing = false;
				}).catch(() => {
					this.loading[p] = false;
					this.refreshing = false;
					this.pages[p].noMore = true;
					showNotify({
						type: 'danger',
						message: "网络错误或未登录"
					});
				})
			},
			acceptOfferButtonHandler(data) {
				showConfirmDialog({
						title: '是否帮助此同学?',
						message: 'ta的需求:' + data.title,
					})
					.then(() => {
						// on confirm
						this.$axios({
							url: url.ip + '/api-offer' + '/offer/accept/' + data.id,
							method: 'GET',
							headers: {
								token: this.$cookies.get('token'),
							}
						}).then((res) => {
							if (res.data.code !== 0) {
								console.log(res);
								showNotify({
									type: 'danger',
									message: res.data.message
								});
							} else {
								showNotify({
									type: 'success',
									message: "已同意帮忙"
								});
							}
						}).catch((err) => {
							console.log(err);
						})
					})
					.catch(() => {
						showNotify({
							type: 'warning',
							message: "已取消帮忙"
						});
					});
			},



			// 商品
			showDetailPage(data) {
				this.detailPageData = data;
				this.detailPageFlash = true;
				this.detailPage = true;
			},

			showPayHandler() {
				showLoadingToast({
					message: '加载中...',
					forbidClick: true,
				});
				setTimeout(this.showPay, 1000);
			},

			detailPageCloseEvent() {
				setTimeout(() => {
					this.detailPageFlash = false
				}, 300);
				return true;
			},
			
			closeDetailPage(){
				this.detailPage=false;
			}
		},
	};
</script>

<style>
	.user-top {
		width: 100%;
		/* height: 40vh; */
		background: url(https://ts1.cn.mm.bing.net/th/id/R-C.511411bb85a468c74dfd18fae28c479c?rik=jGEHEZpLDrgyMg&riu=http%3a%2f%2fwww.jdxzz.com%2fuploads%2fallimg%2f190928%2f3-1Z92Q13457.jpg&ehk=Jo7c6GJCPuSGECiqckTzXvXX58r3UE8JXSwK%2fXiE%2bFk%3d&risl=&pid=ImgRaw&r=0);
		background-repeat: no-repeat;
	}

	.halfCard {
		background: linear-gradient(to bottom, rgba(0, 0, 0, 0) calc(5vw + 2vh), rgba(0, 0, 0, 0) 1px, white 1px, white calc(100% - (5vw + 2vh) - 2px));
		width: 100vw;
	}
</style>